package com.wang.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.Random;

/**
 * ip加密工具类
 */
@Component
@Slf4j
public class CommonUtil {
    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        return ipAddress;
    }


    /**
     * MD5加密
     * @param data
     * @return
     */
    // 建议：可考虑引入 Apache Commons Codec 等工具库简化代码      ai建议
    public static String MD5(String data)  {
        try {
            java.security.MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }

            return sb.toString().toUpperCase();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密过程中发生异常", e);
        }
    }

    /**
     * 获取验证码随机数
     * @param length
     * @return
     */
    public static String getRandomCode(int length){
        String sources = "0123456789";
        Random random = new Random();
        StringBuffer flag = new StringBuffer();
        for(int i = 0;i < length;i++){
            flag.append(sources.charAt(random.nextInt(9)));
        }
        return flag.toString();
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public static long getCurrentTimesTamp(){
        return System.currentTimeMillis();
    }

    /**
     * 生成随机uuid
     * @return
     */
    public String generateUUID() {
        //返回32位字符串   replace("-", ""): 去掉字符串中的“-”   UUID生成的字符串会有“-”
        return java.util.UUID.randomUUID().toString().replace("-", "").substring(0,32);
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    private static final  String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    public static String getStringNumRandom(int length){
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for(int i = 0;i < length;i++){
            result.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
        }
        return result.toString();
    }

    /**
     * 发送json数据给前端
     * @param response
     * @param object
     */
    public static void sendJsonMessage(HttpServletResponse response, Object object){
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");//设置响应头类型
        try(PrintWriter writer = response.getWriter()) {
            writer.write(objectMapper.writeValueAsString(object));
            response.flushBuffer();
        }catch (Exception e){
            log.warn("响应json失败");
        }
    }

}
